import axios from 'axios'
import {
	Notification
} from '@arco-design/web-vue';
import router from '@/router'
import {
	getToken, removeToken
} from '@/utils/token'
import { debounce } from '@/utils';

import config from '../config';
console.log(config);


let VUE_APP_API = import.meta.env.VUE_APP_API as string
//@ts-ignore
let baseURL = config.baseUrl[VUE_APP_API || 'dev']
console.log('当前接口环境:' + VUE_APP_API)
console.log("baseURL", baseURL)
var defaultHttp = axios.create({
	baseURL: baseURL,
	timeout: 10000,
	headers: {
		'Content-Type': 'application/json'
	}
})

var toast401 = debounce(function () {
	Notification.error({
		content: '未登录或登陆过期，请重新登录',
	})
}, 1000, true)

defaultHttp.interceptors.request.use(function (config) {
	// 在发送请求之前做些什么
	var token = getToken()
	config.headers!['Authorization'] = 'bearer ' + token || ""
	return config
}, function (error) {
	// 对请求错误做些什么
	return Promise.reject(error)
})

// 添加响应拦截器
defaultHttp.interceptors.response.use(function (response) {
	// 对响应数据做点什么
	if (response.data.code == 401 || response.data.code == 403) {
		console.log('登录过期')
		toast401()
		removeToken()
		router.push('/login')

		return Promise.reject(response.data)
	} else if (response.data.code != 0 && (response.data.code + '').length != 9) {
		Notification.error({
			content: response.data.message || '未知错误',
		})
		return Promise.reject(response.data)
	}
	return response.data
}, function (error) {
	// 对响应错误做点什么

	if (!error.response) {
		Notification.error({
			content: '服务器错误或未知错误',
		})
	} else if (error.response.status == 401 || error.response.status == 403) {
		toast401()
		removeToken()
		router.push('/login')
	}
	return Promise.reject(error)
})

export default defaultHttp
